﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;

namespace Simp.Model.CoreExpressions.Sequences
{
	/// <summary>Encapsulates an expression cumulating application of an expression over a sequence.</summary>
	/// <remarks>
	/// <para>
	/// For instance, <c>Cumulate({a, b, c}, f)</c> will yield <c>{a, f(a,b), f(f(a,b), c)}</c>.
	/// </para>
	/// <para>
	/// A typical application is with the <c>Addition</c> function where the cumulate function yields the corresponding serie.
	/// </para>
	/// </remarks>
	[ExpressionName("Cumulate")]
	[ParameterPolicy("source", "f")]
	[DebuggerDisplay("{ExpressionHelper.Serialize(this)}")]
	public class CumulateFunction : ISequenceExpression
	{
		#region Inner Types
		private class CumulateSequenceAccessor : ISequenceAccessor
		{
			private readonly ISequenceAccessor _sourceAccessor;
			private readonly IExpression _f;

			public CumulateSequenceAccessor(ISequenceAccessor sourceAccessor, IExpression f)
			{
				_sourceAccessor = sourceAccessor;
				_f = f;
			}

			#region ISequenceAccessor Members
			int ISequenceAccessor.Count
			{
				get { return _sourceAccessor.Count; }
			}

			IExpression ISequenceAccessor.this[int index]
			{
				get
				{
					foreach (IExpression cumulatedElement in this)
					{
						if (index == 0)
						{
							return ExpressionHelper.Simplify(false, cumulatedElement, SimplificationMode.PerfectEquivalent);
						}
						--index;
					}

					throw new NotSupportedException("This point should never be reached");
				}
			}
			#endregion

			#region IEnumerable<IExpression> Members
			IEnumerator<IExpression> IEnumerable<IExpression>.GetEnumerator()
			{
				IExpression cumulator = null;

				foreach (IExpression sourceElement in _sourceAccessor)
				{
					if (cumulator == null)
					{
						cumulator = sourceElement;
					}
					else
					{
						cumulator = new CompositeExpression(new BoundCallingExpression(3), _f, cumulator, sourceElement);
					}

					yield return cumulator;
				}
			}
			#endregion

			#region IEnumerable Members
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<IExpression>)this).GetEnumerator();
			}
			#endregion
		}
		#endregion

		#region ISequenceExpression Members
		ISequenceAccessor ISequenceExpression.GetAccessor(params IExpression[] parameters)
		{
			if (parameters == null)
			{
				throw new ArgumentNullException("parameters");
			}
			if (parameters.Length == 2)
			{
				IExpression source = parameters[0];
				IExpression f = parameters[1];
				ISequenceAccessor accessor = ExpressionHelper.GetAccessor(source);

				if (accessor != null)
				{
					return new CumulateSequenceAccessor(accessor, f);
				}
			}

			return null;
		}
		#endregion
	}
}